package com.supinfo.food.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import com.supinfo.food.dao.UserDao;
import com.supinfo.food.entities.User;

/**
 * User DAO implementation
 * 
 * @author Keitaro
 */
public class JpaUserDao implements UserDao {

	/** Entity manager */
	private EntityManager entityManager;

	public JpaUserDao() {
		entityManager = ManagerDAO.getEntityManager();
	}

	@Override
	public User get(Long id) {
		try {
			return entityManager.find(User.class, id);
		} catch (NoResultException e) {
			return null;
		}
	}

	@Override
	public User get(String login) {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<User> query = cb.createQuery(User.class);
		Root<User> user = query.from(User.class);
		query.where(cb.equal(user.get("login"), login));
		try {
			return entityManager.createQuery(query).getSingleResult();
		} catch (NoResultException e) {
			return null;
		}
	}

	@Override
	public User persist(User user) {
		entityManager.getTransaction().begin();
		entityManager.persist(user);
		entityManager.getTransaction().commit();
		return user;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<User> getAll() {
		return entityManager.createQuery("SELECT m FROM User m").getResultList();
	}

	@Override
	public void delete(Long id) {
		User user = get(id);
		if (user != null) {
			entityManager.getTransaction().begin();
			entityManager.remove(user);
			entityManager.getTransaction().commit();
		}
	}

}
